<?php

namespace app\index\service;

use app\common\dao\SettingDao;
use app\common\model\AccessLog;
use app\common\model\Area;
use app\common\model\ConsultingQuestion;
use app\common\model\Lawsuit;
use app\common\model\PromotionGroup;
use app\common\service\ARYPushQueueService;
use app\index\dao\LawsuitDao;
use app\index\model\UM as UM;
use think\exception\ValidateException;
use think\facade\Config;

/**
 * Class LawsuitService
 * @package app\index\service
 */
class LawsuitService
{
    // dao
    private LawsuitDao $lawsuitDao;

    public function __construct(LawsuitDao $lawsuitDao)
    {
        $this->lawsuitDao = $lawsuitDao;
    }

    public function read(UM $user, $id): Lawsuit
    {

        return $this->lawsuitDao->findByPK($id);
    }

    /**
     * 打官司，第1步
     * @param UM $user
     * @param array $params
     * @return Lawsuit
     */
    public function addStep1(UM $user, array $params): Lawsuit
    {
        $memberId = $user->id;
        $phone = $user->phone;

        $ask = $params['ask'] ?? '';
        $categoryId = $params['categoryId'] ?? null;
        $moneyId = $params['moneyId'] ?? null;
        $provinceId = $params['provinceId'] ?? null;
        $cityId = $params['cityId'] ?? null;
        $channel = $params['channel'] ?? '';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (is_id($promotionGroupId)) {
            $promotionGroup = PromotionGroup::where('id', $promotionGroupId)->find();
            if ($promotionGroup) {
                $channel = $promotionGroup->channel;
            }
        }

        if (is_blank($ask)) {
            throw new ValidateException('请输入您的问题');
        }
        $minWord = Config::get('landing.minWord', 2);
        if (not_blank($ask) && mb_strlen($ask) < $minWord) {
            throw new ValidateException('描述至少' . $minWord . '字，请继续补充');
        }
        if (!is_id($cityId)) {
            throw new ValidateException('请选择案件城市');
        }
        if (!is_id($moneyId)) {
            throw new ValidateException('请选择案件金额');
        }
        if (!is_id($categoryId)) {
            throw new ValidateException('请选择一个案件类型');
        }

        if (!is_id($provinceId) && is_id($cityId)) {
            $city = Area::where('id', $cityId)->find();
            if ($city) {
                $provinceId = $city->pid;
            }
        }

        $aryMatch= 0;
        if($pf == AccessLog::PF_H5){
            $aryMatch = $this->getSettingDao()->getValueByKey('aryMatch', 0);
        }

        // 添加问题
        $question = $this->getQuestionService()->saveQuestion($memberId, $ask, $categoryId, ConsultingQuestion::SOURCE_H5, ConsultingQuestion::FROM_LAWSUIT, false,
            $channel, $pf, $chain, $promotionGroupId);

        // 添加打官司
        $caseParams = [
            'memberId' => $memberId,
            'questionId' => $question->id,
            'ask' => $ask,
            'categoryId' => $categoryId,
            'moneyId' => $moneyId,
            'provinceId' => $provinceId,
            'cityId' => $cityId,
            'phone' => $phone,
            'status' => 0,
            'step' => 1,
            'detailsValid' => details_valid(null),
            'pf' => $pf,
            'chain' => $chain,
            'promotionGroupId' => $promotionGroupId,
            'aryMatch' => $aryMatch,
            // 'alwaysLive' => $alwaysLive,
            // 'isSelf' => $isSelf,
            // 'daysId' => $daysId,
            // 'employLawyer' => $employLawyer,
        ];

        $record = $this->lawsuitDao->insertActive($caseParams);

        // 延迟推送到案如云
        $this->getARYPushQueueService()->pushLawsuit($record->id);

        return $record;
    }

    /**
     * 打官司，第2步
     * @param UM $user
     * @param array $params
     * @return Lawsuit
     */
    public function addStep2(UM $user, array $params): Lawsuit
    {

        $id = $params['id'] ?? null;
        $params['details'] ??= [];
        $params['detailsValid'] = details_valid($params['details']);

        if (!is_id($id)) {
            throw new ValidateException('请选择一个案件');
        }

        $record = Lawsuit::where('id', $id)->find();

        if (is_null($record)) {
            throw new ValidateException('该案件不存在或已被删除');
        }

        if ($record->memberId != $user->id) {
            throw new ValidateException('您只能修改自己的案件');
        }

        if ($record->step != 1 && $record->step != 2) {
            throw new ValidateException('案件状态错误');
        }

        // 修改
        $allowField = ['step', 'details', 'detailsValid', 'isSelf', 'alwaysLive', 'contract', 'injuryMoney', 'injury'];
        $this->lawsuitDao->updateActive($record, $params, $allowField);

        return $record;
    }

    private function getQuestionService(): QuestionService
    {
        return app(QuestionService::class);
    }

    private function getARYPushQueueService(): ARYPushQueueService
    {
        return app(ARYPushQueueService::class);
    }

    private function getSettingDao(): SettingDao
    {
        return app(SettingDao::class);
    }
}
